const router = require('express').Router()
const validateToken = require('../../../../common/validateToken')
const status_code = require('../../../../common/status_code')
const db = require('../../../../db/async-db')
const { to } = require('await-to-js')
const bcrypt = require('bcryptjs')
const Bee = require('../../../../common/bee/bee')

router.post('/update/password', async (req, resp) => {
  // 错误处理
  const handleError = (errCode, error) => {
    resp.json({
      code: errCode,
      msg: status_code[errCode],
    })
    console.error(error)
  }

  // 从请求头里取出 token
  const rawToken = req.headers.authorization
  // 验证token
  const [validateTokenError, validateTokenSuccess] = await to(
    validateToken(rawToken)
  )
  // 验证不通过处理
  if (validateTokenError || !validateTokenSuccess)
    return handleError(66013, validateTokenError)

  const { uid, pwd } = req.body
  if (!Bee.StringUtils.isNotBlank(uid) || !Bee.StringUtils.isNotBlank(pwd))
    return handleError(10003, '参数错误')

  // 生成salt的迭代次数
  const saltRounds = 10
  // 随机生成salt
  const salt = bcrypt.genSaltSync(saltRounds)
  // 生成密码加密后的值
  const saltPassword = bcrypt.hashSync(pwd, salt)

  const [updatePasswordError, updatePasswordSuccess] = await to(
    db.query('UPDATE users SET pwd=? WHERE id=?', [saltPassword, uid])
  )
  if (updatePasswordError || !updatePasswordSuccess)
    return handleError(66013, updatePasswordError)

  if (updatePasswordSuccess.affectedRows === 0) {
    return handleError(-1, '系统错误')
  }
  resp.json({
    code: 0,
    msg: status_code[0],
  })
})

module.exports = router
